package com.tencent.apps.ui.fragment;

import java.util.ArrayList;
import java.util.List;

import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.tencent.apps.R;
import com.tencent.apps.bean.Subject;
import com.tencent.apps.global.AppsApplication;
import com.tencent.apps.http.HttpHelper;
import com.tencent.apps.http.Url;
import com.tencent.apps.ui.adapter.SubjectAdapter;
import com.tencent.apps.utils.CommonUtil;
import com.tencent.apps.utils.GsonUtil;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class SubjectFragment extends BaseFragment {
	private PullToRefreshListView ptrListView;
	private ListView listView;
	public ArrayList<Subject> list = new ArrayList<Subject>();
	private SubjectAdapter adapter;
	@Override
	protected Object requestData() {
		String json = HttpHelper.get(Url.HOME_SUBJECT +list.size());
		List<Subject> subjectList = (List<Subject>) GsonUtil.jsonToList(json, new TypeToken<List<Subject>>() {}.getType());
		
		if (subjectList != null) {
			list.addAll(subjectList);
			//跟新UI
			CommonUtil.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					adapter.notifyDataSetChanged();
					ptrListView.onRefreshComplete();
				}
			});
		}
		return subjectList;
	}

	@Override
	protected View getSuccessView() {
		initptrListView();
		
		initListView();
		
		return ptrListView;
	}

	public void initListView() {
		listView = ptrListView.getRefreshableView();
		listView.setDividerHeight(0);
		listView.setSelector(android.R.color.transparent);
		
		adapter = new SubjectAdapter(list, context);
		listView.setAdapter(adapter);
	}

	public void initptrListView() {
		ptrListView = (PullToRefreshListView) View.inflate(context, R.layout.ptr_listview, null);
		ptrListView.setMode(Mode.BOTH);
		ptrListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			//由于上拉+下拉都是用同一个监听
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				if (ptrListView.getCurrentMode() == Mode.PULL_FROM_START) {
					//更新UI
					CommonUtil.runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							ptrListView.onRefreshComplete();
						}
					});
				} else {
					contentPager.loadAndRefreshData();
				}
			}
		});
	}
}
